import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sinosheets/route/app_router.dart';
import 'package:sinosheets/utils/common_utils/log_util.dart';

import 'route_paths.dart';

///自定义路由观察器
class GBRouteObserver extends NavigatorObserver {
  static List<Route<dynamic>> routeStack = [];

  @override
  void didPush(Route route, Route? previousRoute) {
    routeStack.add(route);
    LogUtil.e("路由堆栈: ${routeStack.map((e) => e.settings.name ?? e.hashCode)}");
    deleteCheckoutRoutes();
  }

  @override
  void didPop(Route route, Route? previousRoute) {
    routeStack.remove(route);
    LogUtil.e("路由堆栈: ${routeStack.map((e) => e.settings.name ?? e.hashCode)}");
  }

// 定义需要移除的路由名称集合
  static final _targetPayRouteNames = {
    '/checkout',
    '/web_pay',
    '/warehouse_return_exchange',
    '/confirm_order',
    '/submit_package',
    '/activity_confirm_order',
  };
  static final _targetRePayRouteNames = {'gobuy_alert_repay'};

  // 检查并修改路由堆栈
  static void deletePayRoutes() {
    //如果路由的堆栈里面 有个名字是gobuy_alert_repay的话就return
    if (routeStack.any((element) => element.settings.name == 'gobuy_alert_repay')) {
      final currentRoute = routeStack.last;
      if (currentRoute.settings.name == '/pay_success') {
        final deleteRoutes = routeStack
            .where(
              (route) => _targetRePayRouteNames.contains(route.settings.name),
            )
            .toList();
        // 延迟到下一个事件循环执行
        Future.microtask(() {
          for (final route in deleteRoutes) {
            if (navigator != null && routeStack.contains(route)) {
              routeStack.remove(route);
              navigator!.removeRoute(route);
            }
          }
        });
      }
    } else {
      final currentRoute = routeStack.last;
      if (currentRoute.settings.name == '/pay_success') {
        final deleteRoutes = routeStack
            .where(
              (route) => _targetPayRouteNames.contains(route.settings.name),
            )
            .toList();
        // 延迟到下一个事件循环执行
        Future.microtask(() {
          for (final route in deleteRoutes) {
            if (navigator != null && routeStack.contains(route)) {
              routeStack.remove(route);
              navigator!.removeRoute(route);
            }
          }
        });
      }
    }
  }

  static final _targetCheckoutRouteNames = {
    '/confirm_order',
    '/submit_package',
    '/warehouse_return_exchange',
    '/warehouse_detail',
    '/activity_confirm_order',
  };

  void deleteCheckoutRoutes() {
    //如果路由的堆栈里面 有个名字是gobuy_alert_repay的话就return
    if (routeStack.any((element) => element.settings.name == 'gobuy_alert_repay')) {
      return;
    }
    final currentRoute = routeStack.last;
    if (currentRoute.settings.name == '/checkout') {
      final deleteRoutes = routeStack
          .where(
            (route) => _targetCheckoutRouteNames.contains(route.settings.name),
          )
          .toList();
      // 延迟到下一个事件循环执行
      Future.microtask(() {
        for (final route in deleteRoutes) {
          if (navigator != null && routeStack.contains(route)) {
            routeStack.remove(route);
            navigator!.removeRoute(route);
          }
        }
      });
    }
  }

  static final _targetActivityConfirmOrderRouteNames = {
    '/activity_confirm_order',
  };

  void deleteActivityConfirmOrderRoutes() {
    final currentRoute = routeStack.last;
    if (currentRoute.settings.name == '/activity_confirm_success') {
      final deleteRoutes = routeStack
          .where(
            (route) => _targetActivityConfirmOrderRouteNames.contains(route.settings.name),
          )
          .toList();
      Future.microtask(() {
        for (final route in deleteRoutes) {
          if (navigator != null && routeStack.contains(route)) {
            routeStack.remove(route);
            navigator!.removeRoute(route);
          }
        }
      });
    }
  }
}

class RouteUtils {
  RouteUtils._internal();
  static final RouteUtils _instance = RouteUtils._internal();
  factory RouteUtils() => _instance;

  static String getCurrentRoute() {
    return Get.currentRoute;
  }

  static void backToHome() {
    AppRouter.backToHome();
  }

  static void toCategoryProduct({
    required String categoryId,
    required String categoryName,
  }) {
    AppRouter.toNamed(RoutePaths.categoryProduct, arguments: {'categoryId': categoryId, 'categoryName': categoryName});
  }

  static void toWebView({
    required String url,
    String title = '',
    SinoWebLoadType type = SinoWebLoadType.url,
  }) {
    AppRouter.toWebView(url: url, title: title, type: type);
  }

  static void toSearch({
    required String keyword,
  }) {
    AppRouter.toNamed(RoutePaths.searchProduct, arguments: {'keyword': keyword});
  }

  //关于我们
  static void toAboutUs() {
    AppRouter.toNamed(RoutePaths.aboutUs);
  }

  //添加Code
  static void toAddCode() {
    AppRouter.toNamed(RoutePaths.addCode);
  }

  /// 打开国家页面，返回国家map
  static Future<Map> openCountryList(List countryList, List hotCountry, Map select, {bool isShowChina = true}) async {
    var back = await AppRouter.toNamed(
      RoutePaths.countryList,
      arguments: {'countryList': countryList, 'hotCountry': hotCountry, 'select': select, 'isShowChina': isShowChina},
    );
    if (back != null && back is Map) {
      return back;
    }
    return {};
  }

  /// 打开线路列表页面，返回线路map
  static Future<Map> openShippingLineList(List? data, {bool isEstimate = false, bool isPreview = false, Map selectItem = const {}}) async {
    var back = await AppRouter.toNamed(RoutePaths.shippingLineList, arguments: {
      "data": data,
      "isEstimate": isEstimate,
      "isPreview": isPreview,
      "selectItem": selectItem,
    });
    if (back != null && back is Map) {
      return back;
    }
    return {};
  }

  static void toLoginAgent() {
    AppRouter.toNamed(RoutePaths.agentLogin);
  }

  ///收藏页面
  static void toFavorite() {
    AppRouter.toNamed(RoutePaths.favorite);
  }

  ///分类页面
  static void toCategory() {
    AppRouter.toNamed(RoutePaths.category);
  }

  ///推荐店铺页面
  static void toRecommendedShop(List shopList) {
    AppRouter.toNamed(RoutePaths.recommendedShop, arguments: {'shopList': shopList});
  }

  ///免费礼物页面
  static void toFreeGifts(List zeroAndDiscountList) {
    AppRouter.toNamed(RoutePaths.freeGifts, arguments: {'zeroAndDiscountList': zeroAndDiscountList});
  }

  ///热门分类页面
  static void toHotCategory() {
    AppRouter.toNamed(RoutePaths.hotCategory);
  }

  ///产品详情页面
  static void toProductDetail(Map productInfo, {bool fromFreeGifts = false}) {
    AppRouter.toNamed(RoutePaths.productDetail, arguments: {'productInfo': productInfo, 'fromFreeGifts': fromFreeGifts});
  }

  ///普货分类页面
  static void toNoemalCategoryPList(String categoryId, String categoryName) {
    AppRouter.toNamed(RoutePaths.noemalCategoryPList, arguments: {'categoryId': categoryId, 'categoryName': categoryName});
  }
}
